package com.imist.nettybasic4.server.handler;

import com.imist.nettybasic4.protocol.request.MessageRequestPacket;
import com.imist.nettybasic4.protocol.response.MessageResponsePacket;
import com.imist.nettybasic4.session.Session;
import com.imist.nettybasic4.utils.SessionUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    public static final MessageRequestHandler INSTANCE = new MessageRequestHandler();

    protected MessageRequestHandler() {
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket messageRequestPacket) throws Exception {
        //1.拿到消息发送方的会话消息
        Session session = SessionUtils.getSession(ctx.channel());

        //2. 通过消息发送方 的会话信息构造要发送的会话消息
        MessageResponsePacket messageResponsePacket = new MessageResponsePacket();
        messageResponsePacket.setMessage(messageRequestPacket.getMessage());
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUserName(session.getUserName());

        //3. 拿到消息接收方的channel

        Channel toUserChannel = SessionUtils.getChannel(messageRequestPacket.getToUserId());

        // 4. 将消息发送给接收方
        if (toUserChannel != null && SessionUtils.hasLogin(toUserChannel)){
            //ctx.channel().writeAndFlush(messageResponsePacket); //需要拿到接收方的连接不然就相当于自己发给自己
            toUserChannel.writeAndFlush(messageResponsePacket);
        }else {
            System.out.println("["+messageRequestPacket.getToUserId()+"} 不在线，发送失败" );
        }


    }
}
